package com.spzx.order.configure;

import org.objenesis.ObjenesisException;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


/**
 * ClassName: DelayedMqConfig
 * Package: com.spzx.order.configure
 * Description:这段代码创建了一个延迟队列，并将其绑定到延迟交换机上。
 * 当消息到达延迟队列时，只有当消息的延迟时间超过队列的延迟时间时，才能从队列中取出并处理。
 * 这种机制可以确保在消息量较大时，系统不会因为消息处理速度过慢而造成消息丢失。
 *
 * @Author ycy
 * @Create 2024/9/2 9:25
 * @Version 1.0
 */
@Configuration
public class DelayedMqConfig {
    public static final String exchange_delay = "exchange.delay";
    public static final String routing_delay = "routing.delay";
    public static final String queue_delay_1 = "queue.delay.1";

    @Bean
    public Queue delayQueue1(){
        // 第一个参数是创建 queue 的名字，第二个参数是是否支持持久化
        return new Queue(queue_delay_1, true);
    }

    @Bean
    public CustomExchange delayExchange(){
        Map<String,Object> args = new HashMap<String, Object>();
        args.put("x-delayed-type","direct");
        return new CustomExchange(exchange_delay,"x-delayed-message",true,false,args);
    }

    /**
     * 将上面创建的 延迟队列(delayQueue1) 绑定到 延迟交换机 (delayExchange)
     * 并设置路由键
     * @return
     */
    @Bean
    public Binding delayBinding1(){
        return BindingBuilder
                .bind(delayQueue1()).to(delayExchange()).with(routing_delay).noargs();
    }
}
